import React, { useEffect, useState } from "react";
import { Button, Tooltip } from "antd";
import classnames from "classnames";
import { BoldOutlined, ItalicOutlined, UnderlineOutlined } from "@ant-design/icons";
import "./index.scss";

const FontStyleIconMap = {
    bold: BoldOutlined,
    italic: ItalicOutlined,
    underline: UnderlineOutlined
}
type FontStyleItem = {text: string, value: string, key: string, defaultValue?: string};
interface IFontStylePickerProps {
    options: FontStyleItem[];
    value: {[key: string]: any}
    onChange: (value: any, key: string) => void;
}

const VFontStylePicker: React.FC<IFontStylePickerProps> = (props) => {
    const { options, value, onChange } = props;
    const [stateArr, setStateArr] = useState<{[key: string]: any}>({});
    useEffect(() => {
        const initOption = {};
        options.forEach(item => {
            Reflect.set(initOption, item.key, value?.[item.key] === item.value);
        });
        setStateArr(initOption);
    }, [value, options])
    const handleOnChange = (item: FontStyleItem) => {
        const { key, value } = item;
        stateArr?.[key] ? onChange(item?.defaultValue || "", key) : onChange(value, key);
    }
    const getItemClassnames = (item: FontStyleItem) => {
        const { key } = item;
        return classnames("font-style-picker-btn", {
            "active-btn": stateArr[key]
        })
    }
    return <ul className="font-style-picker-wrapper">
        {
            options.map(item => {
                const Icon = Reflect.get(FontStyleIconMap, item.value);
                return Icon ? <li className="font-style-picker-item" key={item.key}>
                    <Tooltip title={item.text}>
                        <Button  className={getItemClassnames(item)} onClick={() => handleOnChange(item)}><Icon className="font-style-icon-item" /></Button>
                    </Tooltip>
                </li> : null
            })
        }
    </ul>
}

export default VFontStylePicker;